import { View, Text } from '@tarojs/components'
import Taro, { useLaunch, useLoad } from '@tarojs/taro'
import './index.scss'
import { useState } from 'react'

export default function Index () {
  const [socketTask, setSocketTask] = useState()
  useLoad(() => {
    Taro.connectSocket({
      // url: 'wss://echo.websocket.org',
      url:"ws://dev-chew.yunzhanghu.net/api/v1/mp_visitor_chat/wss_completion?content=你好啊&session_id=a24b7f5d-b12c-4dae-9114-7a43a3b7793b&parent_message_id=24&member_id=1234",
      header: {
        "content-type": "application/json",
        "X-App-Id": 1,
        "X-App-Type": 5,
        "X-Device-Id": "391e0931-75ce-457d-b296-d2e8c008d36a",
        "X-Device-Id-Code": 9,
        "X-Device-Type": "1",
        "X-Os": 2,
        "X-Os-Version": null,
        "X-Access-Token": "eyJhbGciOiJSUzUxMiIsInR5cCI6IkpXVCJ9.eyJhcHBJZCI6MSwiZGV2VXVpZCI6IjM5MWUwOTMxLTc1Y2UtNDU3ZC1iMjk2LWQyZThjMDA4ZDM2YSIsImV4cCI6MTc0NDAwMjc3OSwidG9rZW5UeXBlIjoxLCJ1aWQiOiIxMzU0OTcxMjIzMDk2MTc2NjQzIn0.CcdRxU3mWDFGUTdhLoflcb5TCs52DSZQHbxp3mitd0zJfrGC2VcrfrmuYkahy6nVF968p9VCKRkDqgGkILmTm_iTN7cYjCE6nel-jmjBuVyc46QK4tq0bZZqH6sBmqS6jHJqMhnFbcaezy2coc6UkU9DBlIi5nYSs8EI5WA2P6oOZcX_kVTHgDqV0ymguTI6x55IamM1zTrVkzObt4fMrjRNHBlscFJo1xTOQgKSVpfs1MfrkrT8ol4yR-kwtfni16qxwYMhLt2oSwzWkkcIo5Hx27EnruXhGyUAp5Lm0szU0NeReUbLEuP56iYLlcb3HI7kQWXqi4Kk1-8VMowZzg",
        "X-Member-Id": "1358139363099553794",
        "x-yzh-env": "yzhapp-702",
        "x-device-type": 1,
        "x-os-version": null
    },
      success: function (res) {
        console.log('connectSocket success', res);
      },
      fail: function (err) {
        console.error('connectSocket fail', err);
      }
    }).then(task => {
      task.onOpen(() => {
        console.log('WebSocket connection opened');
        // task.send({ data: '123' });
        setSocketTask(task)
      });

      task.onMessage(msg => {
        console.log('Received message:', msg.data);
        // task.close();
      });

      task.onError(err => {
        console.error('WebSocket error:', err);
      });

      task.onClose(e => {
        console.log('WebSocket closed:', e);
      });
    });


    console.log('App launched.')
  })

  const handClick = () => {
    socketTask.send({ data: 'fffff' });
  }

  return (
    <View className='index'>
      <Text onClick={handClick}>Hello world!</Text>
    </View>
  )
}
